package com.actionpals.utils
{
	/**
	 * The RegExpUtil utility is an all-static class with methods for working with regular expressions.
	 * You do not create instances of RegExpUtil; instead you call static methods such as RegExpUtil.toRegExp() method.
	 * 
	 * @author Mark Walters
	 */	
	public class RegExpUtil
	{
		/**
		 * Outputs the regular expression value of a string.
		 * String input must be in regular expression literal format ( eg: "/bob/i" ).
		 * This is useful for dynamically building regular expressions (eg: a single String input from XML).
		 * 
		 * @param input The string value to output as RegExp.
		 * @return RegExp.
		 */
		public static function toRegExp( input:String ):RegExp
		{
			if( !isRegExLiteral( input ) ) return null;
			
			var pattern:String = input.slice( 1, input.lastIndexOf( "/" ) );
			pattern = pattern.replace( /\"/g, "\\\"" );
			var flags:String = input.slice( input.lastIndexOf( "/" ) + 1, input.length );
			
			return new RegExp( pattern, flags );
		}
		
		/**
		 * Checks if input String follows regular expression literal syntax ( eg: "/bob/i" ).
		 * 
		 * @param input The string value to check.
		 * @returns A boolean value indicating whether the string follows regular expression literal syntax.
		 */
		public static function isRegExLiteral( input:String ):Boolean
		{
			return ( input.slice( 0, 1 ) != "/" || input.lastIndexOf( "/" ) == input.indexOf( "/" ) ) ? false : true;
		}
	}
}